import cv2
import sys
from PyQt6 import uic
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPixmap, QImage, QTextLine
from PyQt6.QtWidgets import QWidget, QApplication, QLabel, QPushButton, QSlider, QComboBox, QFileDialog, QLineEdit, \
    QMessageBox
from OpenCamera import open_camera
from Load_Training_Set import FaceRecognition
import MyQtSql


class LoginWindow(QWidget):
    def __init__(self):
        super().__init__()
        ui = uic.loadUi('./login.ui', self)

        self.saveBtn: QPushButton = ui.saveBtn
        self.exithostBtn: QPushButton = ui.exithostBtn
        self.loginBtn: QPushButton = ui.loginBtn

        self.saveBtn.clicked.connect(self.saveBtn_slot)
        self.exithostBtn.clicked.connect(self.exithostBtn_slot)
        self.loginBtn.clicked.connect(self.loginBtn_slot)
        self.loginBtn_num = 0

        self.backgroundLabel: QLabel = ui.backgroundLabel
        self.logoLab: QLabel = ui.logoLab
        self.userNameLab: QLabel = ui.userNameLab
        self.passwdLab: QLabel = ui.passwdLab
        self.savelabel: QLabel = ui.savelabel


        self.userNameLine: QLineEdit = ui.userNameLine
        self.passwdLine: QLineEdit = ui.passwdLine

        self.userNameLine.setPlaceholderText("请输入用户名")
        self.passwdLine.setPlaceholderText("请输入密码")

        self.passwdLine.setEchoMode(QLineEdit.EchoMode.Password)

        self.backgroundLabel.setPixmap(QPixmap("data/background.jpg"))
        self.backgroundLabel.setScaledContents(True)

        self.logoLab.setStyleSheet("background: transparent;")
        self.logoLab.setPixmap(QPixmap("data/img.png"))
        self.logoLab.setScaledContents(True)

        self.savelabel.setScaledContents(True)
        self.savelabel.setStyleSheet("background: transparent;")
        # 居中
        self.savelabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.savelabel.setStyleSheet("font-size: 20px;font-weight: bold;")

        self.userNameLab.setStyleSheet("background: transparent;")
        self.userNameLab.setPixmap(QPixmap("data/name.png"))
        self.userNameLab.setScaledContents(True)

        self.passwdLab.setStyleSheet("background: transparent;")
        self.passwdLab.setPixmap(QPixmap("data/lock.png"))
        self.passwdLab.setScaledContents(True)

    def exithostBtn_slot(self):
        loginwindow.close()
        myWidget.show()

    def saveBtn_slot(self):
        loginwindow.hide()
        # 读取用户名和密码
        username = self.userNameLine.text()
        password = self.passwdLine.text()
        print(f"用户名: {username}, 密码: {password}")

        if self.savelabel.text() == "登录":
            user_id = MyQtSql.check_login(username, password)

            if user_id:  # 用户 ID 存在，表示登录成功
                MyQtSql.insert_login_record(user_id)  # 记录登录信息
                open_camera(username)  # 打开摄像头
            else:
                QMessageBox.warning(self, "警告", "用户名或密码错误")

        else:
            # self.savelabel.text() == "注册"
            # 读取用户名和密码
            if MyQtSql.check_user_exists(username):
                QMessageBox.warning(self, "警告", "用户名已存在")
            else:
                MyQtSql.insert_user(username, password)
                open_camera(username)  # 打开摄像头

        loginwindow.show()

    def loginBtn_slot(self):
        self.loginBtn_num += 1
        # 修改 QLabel 的文本
        if self.loginBtn_num %2 == 1:
            print("切换成注册")
            self.savelabel.setText('注册')
            # 修改 QPushButton 的文本
            self.loginBtn.setText('登录')
        else:
            print("切换成登录")
            self.savelabel.setText('登录')
            self.loginBtn.setText('注册')
            self.loginBtn_num = 0


class MyWidget(QWidget):

    # def cv2_QT_img(self, img):
    #     """将图像从 BGR 转换为 RGB 格式，并显示在 QLabel 中"""
    #     img_QT = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    #     h, w, c = img_QT.shape
    #     bytes_per_line = c * w
    #     q_img = QImage(img_QT.data, w, h, bytes_per_line, QImage.Format.Format_RGB888)
    #
    #     self.label.setPixmap(QPixmap.fromImage(q_img))
    #     self.label.setScaledContents(True)
    #     return q_img

    def __init__(self):
        super().__init__()
        ui = uic.loadUi("./QT.ui", self)

        self.saveCameraBtn: QPushButton = ui.saveCameraBtn
        self.CameraBtn: QPushButton = ui.CameraBtn

        self.label: QLabel = ui.label

        self.label.setStyleSheet("background: transparent;")
        self.label.setPixmap(QPixmap("data/img.png"))
        self.label.setScaledContents(True)


        self.saveCameraBtn.clicked.connect(self.saveCameraBtn_slot)
        self.CameraBtn.clicked.connect(self.Camera_slot)

    def saveCameraBtn_slot(self):
        """打开摄像头保存图片"""
        myWidget.close()
        loginwindow.show()

    def Camera_slot(self):
        """打开监控摄像头"""
        FaceRecognition()

    #
    # def exitBtn_slot(self):
    #     """退出程序"""
    #     sys.exit(0)
    #
    # def writer_slot(self):
    #     # 通过 QFileDialog 弹出文件保存对话框
    #     file_path, _ = QFileDialog.getSaveFileName(
    #         self,  # 父窗口
    #         "保存文件",  # 对话框标题
    #         "",  # 默认路径
    #         "PNG文件 (*.png);;所有文件 (*.*)",  # 文件过滤器
    #     )
    #
    #     if file_path:
    #         cv2.imwrite(file_path, self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWidget = MyWidget()
    loginwindow = LoginWindow()
    # myWidget.setWindowFlags(Qt.WindowType.FramelessWindowHint)

    myWidget.show()
    sys.exit(app.exec())
